package com.yihaodian.server.servlet.rest;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.gson.Gson;
import com.google.inject.Injector;
import com.yihaodian.api.client.BrokerService;
import com.yihaodian.api.common.json.GsonWrapper;
import com.yihaodian.api.search.SearchService;
import com.yihaodian.cluster.Node;
import com.yihaodian.index.meta.shard.ShardId;
import com.yihaodian.server.SearchServiceExporter;

public class AbstractServlet extends HttpServlet {
	private static final Logger logger = Logger
			.getLogger(AbstractServlet.class);

	public static final String param_nodeId = "nodeId";
	public static final String param_shardId = "shardId";
	public static final String param_index_name = "index";

	/**
	 * the real app bean context, all the bean is in Guice Injector.
	 */
	protected Injector injector;

	protected BrokerService brokerService;

	/**
	 * 
	 */
	protected Gson gson = null;

	@Override
	public void init() throws ServletException {
		super.init();

		logger.info(this.getClass() + " init");

		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		SearchServiceExporter exporter = (SearchServiceExporter) context
				.getBean("searchService");
		injector = exporter.getNodeBootstrap().getInjector();

		gson = GsonWrapper.getGson();

		brokerService = injector.getInstance(BrokerService.class);
	}

	protected Node getNode(HttpServletRequest req) {
		String nodeId = req.getParameter(param_nodeId);
		if (nodeId == null)
			return null;

		String[] splits = nodeId.split("_");
		String ip = splits[0];
		String sPort = splits[1];
		int port = Integer.parseInt(sPort);

		return new Node(ip, port);
	}

	protected ShardId getShardId(HttpServletRequest req) {
		String shardId = req.getParameter(param_shardId);
		if (shardId == null)
			return null;

		String[] splits = shardId.split("_");
		String index = splits[0];
		String shard = splits[1];

		return new ShardId(index, shard);
	}

	protected String getIndexName(HttpServletRequest req) {
		String index = req.getParameter(param_index_name);
		if (index == null) {
			String url = req.getRequestURI();
			if (url.charAt(url.length() - 1) == '/')
				url = url.substring(0, url.length() - 1);
			index = url.substring(url.lastIndexOf('/') + 1, url.length());
		}
		
		return index;
	}

	protected void respJson(HttpServletRequest req, HttpServletResponse resp,
			Object obj) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json; charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Methods", "GET, POST");
		resp.setHeader("Access-Control-Allow-Headers",
				"Origin, Content-Type, X-Requested-With, Accept");

		String json = obj instanceof String ? obj.toString() : gson.toJson(obj);

		OutputStream ostream = resp.getOutputStream();
		ostream.write(json.getBytes("UTF-8"));
		ostream.flush();
	}

	public void respXml(HttpServletRequest req, HttpServletResponse resp,
			String xml) throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/xml; charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Methods", "GET, POST");
		resp.setHeader("Access-Control-Allow-Headers",
				"Origin, Content-Type, X-Requested-With, Accept");

		OutputStream ostream = resp.getOutputStream();
		ostream.write(xml.getBytes("UTF-8"));
		ostream.flush();
	}

}
